#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>


static DECLARE_WAIT_QUEUE_HEAD(button_waitq);

static volatile int ev_press = 0;


static struct class *third_cls;
static struct class_device *third_cls_dev;

struct pin_desc{
	unsigned int pin;
	unsigned int keyval;
};

static unsigned int keyval;

struct pin_desc pins_desc[4] = {
	{S3C2410_GPF0, 0x01},
	{S3C2410_GPF2, 0x02},
	{S3C2410_GPG3, 0x03},
	{S3C2410_GPG11, 0x04},
};

static irqreturn_t button_irq(int irq, void *dev_id)
{
	struct pin_desc *pindesc = (struct pin_desc *)dev_id;
	unsigned int val = s3c2410_gpio_getpin(pindesc->pin);

	if(val == 1)
	{
		keyval = 0x80 | pindesc->keyval;
	}
	else
	{
		keyval = pindesc->keyval;
	}

	ev_press = 1;
	wake_up_interruptible(&button_waitq);
	
	return IRQ_HANDLED;
}

static int third_drv_open(struct inode *inode, struct file *file)
{
	request_irq(IRQ_EINT0 , button_irq, IRQT_BOTHEDGE, "S2", &pins_desc[0]);
	request_irq(IRQ_EINT2 , button_irq, IRQT_BOTHEDGE, "S3", &pins_desc[1]);
	request_irq(IRQ_EINT11, button_irq, IRQT_BOTHEDGE, "S4", &pins_desc[2]);
	request_irq(IRQ_EINT19, button_irq, IRQT_BOTHEDGE, "S5", &pins_desc[3]);

	return 0;
}

static ssize_t third_drv_read(struct file *file, __user char *buf, size_t count, loff_t *ppos)
{
	if(count != 1)
		return -EINVAL;

	wait_event_interruptible(button_waitq, ev_press);
	
	copy_to_user(buf, &keyval, 1);
	ev_press = 0;
	return 1;
}

static int third_drv_close(struct inode *inode, struct file *file)
{
	free_irq(IRQ_EINT0, &pins_desc[0]);
	free_irq(IRQ_EINT2, &pins_desc[1]);
	free_irq(IRQ_EINT11, &pins_desc[2]);
	free_irq(IRQ_EINT19, &pins_desc[3]);
}

static static file_operations third_drv_fops = {
	.owner = THIS_MODULE,
	.open  = third_drv_open,
	.read  = third_drv_read,
	.release = third_drv_close,
};

int major;
static int third_drv_init(void)
{
	major = register_chrdev(0, "third_drv", &third_drv_fops);

	third_cls = class_create(THIS_MODULE, "third_drv");

	third_cls_dev = class_device_create(third_cls, NULL, MKDEV(major, 0), NULL, "third_drv");
	return 0;
}

static void third_drv_exit(void)
{
	unregister_chrdev(major, "third_drv");
	class_device_unregister(third_cls_dev);
	class_destroy(third_cls);
}

module_init(third_drv_init);
module_exit(third_drv_exit);
MODULE_LICENSE("GPL");


